#!/bin/bash

# =============================================================================
# 最终版完整构建脚本（包含PKG）
# LimeReader macOS Release + PKG 构建系统
# =============================================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 配置变量
PROJECT_ROOT=$(pwd)
BUILD_DIR="build"
QT_PATH="/opt/homebrew/opt/qt6"
APP_NAME="LimeReader.app"
CHINESE_APP_NAME="影谷长图处理大师.app"
BUNDLE_ID="com.limereader.app"
VERSION="2.7.2"
PKG_NAME="LimeReader_v${VERSION}_macOS.pkg"
DIST_DIR="dist"

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${PURPLE}[STEP]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_step "检查构建依赖..."

    # 检查Qt
    if [ ! -d "$QT_PATH" ]; then
        log_error "Qt未找到，路径: $QT_PATH"
        exit 1
    fi

    # 检查cmake
    if ! command -v cmake &> /dev/null; then
        log_error "cmake未找到"
        exit 1
    fi

    # 检查pkgbuild
    if ! command -v pkgbuild &> /dev/null; then
        log_error "pkgbuild未找到，请安装Xcode Command Line Tools"
        log_info "运行: xcode-select --install"
        exit 1
    fi

    log_success "所有依赖检查通过"
}

# 清理构建环境
cleanup_build() {
    log_step "清理构建环境..."

    if [ -d "$BUILD_DIR" ]; then
        log_info "清理构建目录..."
        rm -rf "$BUILD_DIR" 2>/dev/null || {
            # 如果删除失败，先删除有问题的.app文件
            find "$BUILD_DIR" -name "*.app" -type d -exec rm -rf {} + 2>/dev/null || true
            rm -rf "$BUILD_DIR" 2>/dev/null || true
        }
    fi

    mkdir -p "$BUILD_DIR"
    log_success "构建环境已清理"
}

# 配置CMake
configure_cmake() {
    log_step "配置CMake..."
    cd "$BUILD_DIR"
    cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$QT_PATH" ..
    cd ..
    log_success "CMake配置完成"
}

# 构建项目
build_project() {
    log_step "执行构建..."
    cd "$BUILD_DIR"
    cmake --build . --config Release --parallel
    cd ..
    log_success "项目构建完成"
}

# 部署Qt依赖
deploy_qt_dependencies() {
    log_step "部署Qt依赖..."
    cd "$BUILD_DIR"
    cmake --build . --target deploy_mac
    cd ..
    log_success "Qt依赖部署完成"
}

# 添加关键依赖
add_missing_dependencies() {
    log_step "添加关键依赖..."

    local app_path="$BUILD_DIR/bin/$APP_NAME"

    # 添加QtDBus框架
    if [ -d "$QT_PATH/lib/QtDBus.framework" ]; then
        cp -r "$QT_PATH/lib/QtDBus.framework" "$app_path/Contents/Frameworks/"
        log_success "QtDBus.framework 已添加"
    else
        log_warning "QtDBus.framework 未找到"
    fi

    # 添加libpoppler
    if [ -f "/opt/homebrew/lib/libpoppler.153.dylib" ]; then
        cp "/opt/homebrew/lib/libpoppler.153.dylib" "$app_path/Contents/Frameworks/"
        log_success "libpoppler.153.dylib 已添加"
    else
        log_warning "libpoppler.153.dylib 未找到"
    fi

    # 修复依赖路径
    local poppler_cpp="$app_path/Contents/Frameworks/libpoppler-cpp.2.dylib"
    if [ -f "$poppler_cpp" ]; then
        install_name_tool -change "@rpath/libpoppler.153.dylib" "@executable_path/../Frameworks/libpoppler.153.dylib" "$poppler_cpp"
        log_success "libpoppler-cpp依赖路径已修复"
    fi
}

# 清理签名冲突
cleanup_signing_conflicts() {
    log_step "清理签名冲突..."

    local app_path="$BUILD_DIR/bin/$APP_NAME"

    # 删除可能导致签名问题的文件
    rm -rf "$app_path/Contents/_CodeSignature" 2>/dev/null || true
    rm -rf "$app_path/Contents/MacOS/icons/" 2>/dev/null || true

    # 清理临时文件
    rm -f "$app_path/Contents/MacOS/config.json" 2>/dev/null || true
    rm -f "$app_path/Contents/MacOS/debug.log" 2>/dev/null || true
    rm -rf "$app_path/Contents/MacOS/cache/" 2>/dev/null || true

    log_success "签名冲突文件已清理"
}

# 代码签名
code_sign_app() {
    log_step "执行代码签名..."

    local app_path="$BUILD_DIR/bin/$APP_NAME"

    # 签名所有框架
    find "$app_path/Contents/Frameworks" -name "*.framework" -exec codesign -f -s - {} \; 2>/dev/null || true

    # 签名所有动态库
    find "$app_path/Contents/Frameworks" -name "*.dylib" -exec codesign -f -s - {} \; 2>/dev/null || true

    # 签名所有插件
    find "$app_path/Contents/PlugIns" -name "*.dylib" -exec codesign -f -s - {} \; 2>/dev/null || true

    # 签名主可执行文件
    codesign -f -s - "$app_path/Contents/MacOS/LimeReader" 2>/dev/null || true

    # 签名整个应用包
    codesign -f -s - "$app_path"

    log_success "代码签名完成"
}

# 验证构建
verify_build() {
    log_step "验证构建结果..."

    local app_path="$BUILD_DIR/bin/$APP_NAME"

    if [ ! -d "$app_path" ]; then
        log_error "应用包未找到: $app_path"
        exit 1
    fi

    if [ ! -f "$app_path/Contents/MacOS/LimeReader" ]; then
        log_error "可执行文件未找到"
        exit 1
    fi

    log_success "构建验证通过"
    log_info "应用路径: $app_path"
}

# 测试应用启动
test_application() {
    log_step "测试应用启动..."

    local app_path="$BUILD_DIR/bin/$APP_NAME"

    # 关闭已运行的实例
    pkill -f "LimeReader" 2>/dev/null || true
    sleep 1

    # 启动应用
    open "$app_path"
    sleep 3

    # 检查进程
    if pgrep -f "LimeReader" > /dev/null; then
        log_success "应用启动成功！"
        log_info "进程信息:"
        pgrep -f "LimeReader" | head -1
    else
        log_warning "应用启动失败，请检查日志"
    fi
}

# 创建PKG包
create_pkg_package() {
    log_step "创建PKG安装包..."

    # 调用可靠的PKG构建脚本
    if [ -f "./create_reliable_pkg.sh" ]; then
        log_info "使用可靠的PKG构建系统..."
        ./create_reliable_pkg.sh
    else
        log_error "未找到可靠的PKG构建脚本"
        return 1
    fi

    if [ -f "$DIST_DIR/$PKG_NAME" ]; then
        local pkg_size=$(du -h "$DIST_DIR/$PKG_NAME" | cut -f1)
        log_success "PKG包创建成功！"
        log_info "文件位置: $DIST_DIR/$PKG_NAME"
        log_info "文件大小: $pkg_size"
        log_info "应用名称: $CHINESE_APP_NAME"
    else
        log_error "PKG包创建失败"
        return 1
    fi
}

# 生成构建报告
generate_build_report() {
    log_step "生成构建报告..."

    local report_file="build_report_$(date +%Y%m%d_%H%M%S).txt"
    local app_path="$BUILD_DIR/bin/$APP_NAME"
    local pkg_path="$DIST_DIR/$PKG_NAME"

    {
        echo "========================================"
        echo "LimeReader macOS 构建报告"
        echo "构建时间: $(date)"
        echo "========================================"
        echo
        echo "构建配置:"
        echo "- 项目版本: $VERSION"
        echo "- 构建类型: Release"
        echo "- Qt路径: $QT_PATH"
        echo "- 应用包位置: $app_path"
        echo
        echo "应用包信息:"
        ls -la "$app_path/Contents/" | head -10
        echo
        echo "依赖信息:"
        otool -L "$app_path/Contents/MacOS/LimeReader" | head -15
        echo
        if [ -f "$pkg_path" ]; then
            echo "PKG信息:"
            echo "- 文件名: $PKG_NAME"
            echo "- 位置: $pkg_path"
            local size=$(du -h "$pkg_path" | cut -f1)
            echo "- 大小: $size"
        else
            echo "PKG信息: 未生成"
        fi
        echo
        echo "构建完成!"
        echo "========================================"
    } > "$report_file"

    log_success "构建报告已生成: $report_file"
}

# 主函数
main() {
    echo -e "${CYAN}"
    echo "========================================"
    echo "  LimeReader 最终版构建 + PKG 打包系统"
    echo "========================================"
    echo

    # 记录开始时间
    local start_time=$(date +%s)

    # 执行构建步骤
    check_dependencies
    cleanup_build
    configure_cmake
    build_project
    deploy_qt_dependencies
    add_missing_dependencies
    cleanup_signing_conflicts
    code_sign_app
    verify_build
    test_application
    create_pkg_package
    generate_build_report

    # 计算构建时间
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))

    echo -e "${GREEN}"
    echo "========================================"
    echo "        🎉 构建成功完成！ 🎊"
    echo "========================================"
    echo -e "${NC}"
    log_success "总构建时间: ${duration}秒"
    log_success "应用包位置: $PROJECT_ROOT/$BUILD_DIR/bin/$APP_NAME"
    log_success "PKG安装包: $PROJECT_ROOT/$DIST_DIR/$PKG_NAME"
    log_info "安装后的应用名称: $CHINESE_APP_NAME"
    echo
    echo -e "${CYAN}📦 分发信息:${NC}"
    echo -e "${YELLOW}  应用包 (开发): $PROJECT_ROOT/$BUILD_DIR/bin/$APP_NAME${NC}"
    echo -e "${YELLOW}  安装包 (用户): $PROJECT_ROOT/$DIST_DIR/$PKG_NAME${NC}"
    echo
    echo -e "${CYAN}🚀 使用方法:${NC}"
    echo -e "${YELLOW}  测试应用: open $PROJECT_ROOT/$BUILD_DIR/bin/$APP_NAME${NC}"
    echo -e "${YELLOW}  安装PKG: open $PROJECT_ROOT/$DIST_DIR/$PKG_NAME${NC}"
    echo
    echo -e "${GREEN}✨ 现在可以分发给用户使用了！${NC}"
}

# 错误处理
handle_error() {
    local exit_code=$?
    log_error "构建失败，错误代码: $exit_code"
    log_info "请检查上面的错误信息"
    exit $exit_code
}

# 设置错误处理
trap handle_error ERR

# 执行主流程
main "$@"